import type { FC } from "react"
import type { MessageDescriptor, PrimitiveType } from "react-intl"
import { FormattedMessage, useIntl } from "react-intl"
import { useSelector } from "react-redux"

import { AppState } from "@/stores"

import en_US from "./en-US"
import { LocaleKey } from "./tempType"
import zh_CN from "./zh-CN"

export const localeConfig = {
	zh_CN: zh_CN as Record<string, string>,
	en_US: en_US as Record<string, string>
} as Record<string, Record<string, string>>

// type Id = keyof typeof en_US

interface Props extends MessageDescriptor {
	id: string
	values?: Record<string, PrimitiveType>
}

export const LocaleFormatter: FC<Props> = ({ ...props }) => {
	const notChildProps = { ...props, children: undefined }

	return <FormattedMessage {...notChildProps} id={props.id} />
}

export type FormatMessageProps = (descriptor: Props, values?: Record<string, PrimitiveType>) => string

export const useLocale = () => {
	const { formatMessage: _formatMessage, ...rest } = useIntl()
	const formatMessage: FormatMessageProps = _formatMessage
	const { locale } = useSelector((state: AppState) => state.global)
	const newFormat = (p: { id: LocaleKey | string } | LocaleKey | string) => {
		// console.log(typeof p)
		const id = typeof p === "object" ? p.id : p
		if (id.startsWith("routes")) {
			return localeConfig[locale][id] ?? (id.split(".").pop() as string)
		}
		const ret = _formatMessage({ id })
		return ret === id ? (ret.split(".").pop() as string) : ret
	}
	const routeFormat: FormatMessageProps = ({ id }) => {
		//因菜单需要翻译的太多，为防止后台太多error消息，暂时手动查询一下匹配项
		return localeConfig[locale][id] ?? (id.split(".").pop() as string)
	}
	// const formatByValue = (value: string) => {
	// 	let key = ""
	// 	Object.keys(localeConfig).some(lang => {
	// 		return Object.keys(localeConfig[lang]).some(item => {
	// 			if (localeConfig[lang][item] === value) {
	// 				key = item
	// 				return true
	// 			} else return false
	// 		})
	// 	})
	// 	if (key) return formatMessage({ id: key })
	// 	else return value
	// }

	return {
		...rest,
		formatMessage,
		newFormat,
		routeFormat
	}
}
